<?php
/**
 * @file
 */

/**
 * The main API function for creating content.
 */
function cjcoupon_extend_generate_content() {
  $content_type = variable_get('cjcoupon_extend_content_type', '');
  $num_nodes = variable_get('cjcoupon_extend_num_nodes', 10);
  $title_length = variable_get('cjcoupon_extend_title_length', 4);
  if ($content_type &&  $num_nodes) {
    // Generate nodes.
    $start = time();
    for ($i = 1; $i <= $num_nodes; $i++) {
      cjcoupon_extend_add_node($content_type, $title_length);
      if (function_exists('drush_log') && $i % drush_get_option('feedback', 1000) == 0) {
        $now = time();
        drush_log(dt('Completed !feedback nodes (!rate nodes/min)', array('!feedback' => drush_get_option('feedback', 1000), '!rate' => (drush_get_option('feedback', 1000)*60)/($now-$start))), 'ok');
        $start = $now;
      }
    }
  }
  drupal_set_message(format_plural($num_nodes, '1 node created.', 'Finished creating @count nodes'));
}

/**
 * Create one node. Used by both batch and non-batch code branches.
 */
function cjcoupon_extend_add_node($content_type, $title_length = 0) {
  $node = new stdClass();
  $node->nid = NULL;

  // Insert new data:
  $node->type = $content_type;
  node_object_prepare($node);
  $node->uid = 1;
  $type = node_type_get_type($node);
  $node->revision = mt_rand(0, 1);
  $node->promote = mt_rand(0, 1);

  if ($type->has_title) {
    // We should not use the random function if the value is not random
    if ($title_length < 2) {
      $node->title = cjcoupon_extend_create_greeking(1, TRUE);
    }
    else {
      $node->title = cjcoupon_extend_create_greeking(mt_rand(1, $title_length), TRUE);
    }
  }

  // Avoid NOTICE.
  if (!isset($results['time_range'])) {
    $results['time_range'] = 0;
  }

  // Add alias.
  if (!isset($results['add_alias'])) {
    $results['add_alias'] = 0;
  }

  // Set language
  $default = language_default('language');
  $node->language =  $default == 'en' ? LANGUAGE_NONE : $default;

  $node->created = REQUEST_TIME - mt_rand(0, $results['time_range']);

  // A flag to let hook_node_insert() implementations know that this is a
  // generated node.
  $node->cjcoupon_extend = $results;

  // Populate all core fields on behalf of field.module
  module_load_include('inc', 'cjcoupon_extend', 'fields.generate');
  cjcoupon_entend_generate_fields($node, 'node', $node->type);

  // See cjcoupon_extend_generate_node_insert() for actions that happen before and after
  // this save.
  node_save($node);
}

/**
 * Handle the cjcoupon_extend request to kill all of the content.
 */
function cjcoupon_extend_content_kill($values) {
  $results = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('type', $values['node_types'], 'IN')
    ->execute();
  foreach ($results as $result) {
    $nids[] = $result->nid;
  }

  if (!empty($nids)) {
    node_delete_multiple($nids);
    drupal_set_message(t('Deleted %count nodes.', array('%count' => count($nids))));
  }
}


function cjcoupon_extend_create_content($type = NULL) {
  $nparas = mt_rand(1,12);
  $type = empty($type) ? mt_rand(0,3) : $type;

  $output = "";
  switch($type % 3) {
    default: // plain text
      for ($i = 1; $i <= $nparas; $i++) {
        $output .= cjcoupon_extend_create_para(mt_rand(10,60)) ."\n\n";
      }
  }

  return $output;
}

function cjcoupon_extend_create_para($words, $type = 0) {
  $output = '';
  switch ($type) {
    case 1:
      $output .= "<p>" . cjcoupon_extend_create_greeking($words)  . "</p>";
      break;

    case 2:
      $output .= cjcoupon_extend_create_greeking($words) . "<br />";
      break;

    default:
      $output .= cjcoupon_extend_create_greeking($words);
  }
  return $output;
}

function cjcoupon_extend_create_greeking($word_count, $title = FALSE) {
  $dictionary = array("abbas", "abdo", "abico", "abigo", "abluo", "accumsan",
    "acsi", "ad", "adipiscing", "aliquam", "aliquip", "amet", "antehabeo",
    "appellatio", "aptent", "at", "augue", "autem", "bene", "blandit",
    "brevitas", "caecus", "camur", "capto", "causa", "cogo", "comis",
    "commodo", "commoveo", "consectetuer", "consequat", "conventio", "cui",
    "damnum", "decet", "defui", "diam", "dignissim", "distineo", "dolor",
    "dolore", "dolus", "duis", "ea", "eligo", "elit", "enim", "erat",
    "eros", "esca", "esse", "et", "eu", "euismod", "eum", "ex", "exerci",
    "exputo", "facilisi", "facilisis", "fere", "feugiat", "gemino",
    "genitus", "gilvus", "gravis", "haero", "hendrerit", "hos", "huic",
    "humo", "iaceo", "ibidem", "ideo", "ille", "illum", "immitto",
    "importunus", "imputo", "in", "incassum", "inhibeo", "interdico",
    "iriure", "iusto", "iustum", "jugis", "jumentum", "jus", "laoreet",
    "lenis", "letalis", "lobortis", "loquor", "lucidus", "luctus", "ludus",
    "luptatum", "macto", "magna", "mauris", "melior", "metuo", "meus",
    "minim", "modo", "molior", "mos", "natu", "neo", "neque", "nibh",
    "nimis", "nisl", "nobis", "nostrud", "nulla", "nunc", "nutus", "obruo",
    "occuro", "odio", "olim", "oppeto", "os", "pagus", "pala", "paratus",
    "patria", "paulatim", "pecus", "persto", "pertineo", "plaga", "pneum",
    "populus", "praemitto", "praesent", "premo", "probo", "proprius",
    "quadrum", "quae", "qui", "quia", "quibus", "quidem", "quidne", "quis",
    "ratis", "refero", "refoveo", "roto", "rusticus", "saepius",
    "sagaciter", "saluto", "scisco", "secundum", "sed", "si", "similis",
    "singularis", "sino", "sit", "sudo", "suscipere", "suscipit", "tamen",
    "tation", "te", "tego", "tincidunt", "torqueo", "tum", "turpis",
    "typicus", "ulciscor", "ullamcorper", "usitas", "ut", "utinam",
    "utrum", "uxor", "valde", "valetudo", "validus", "vel", "velit",
    "veniam", "venio", "vereor", "vero", "verto", "vicis", "vindico",
    "virtus", "voco", "volutpat", "vulpes", "vulputate", "wisi", "ymo",
    "zelus");
  $dictionary_flipped = array_flip($dictionary);

  $greeking = '';

  if (!$title) {
    $words_remaining = $word_count;
    while ($words_remaining > 0) {
      $sentence_length = mt_rand(3, 10);
      $words = array_rand($dictionary_flipped, $sentence_length);
      $sentence = implode(' ', $words);
      $greeking .= ucfirst($sentence) . '. ';
      $words_remaining -= $sentence_length;
    }
  }
  else {
    // Use slightly different method for titles.
    $words = array_rand($dictionary_flipped, $word_count);
    $words = is_array($words) ? implode(' ', $words) : $words;
    $greeking = ucwords($words);
  }

  // Work around possible php garbage collection bug. Without an unset(), this
  // function gets very expensive over many calls (php 5.2.11).
  unset($dictionary, $dictionary_flipped);
  return trim($greeking);
}
